package com.neuedu.jdbc.dao;

import com.neuedu.jdbc.DBUtils;

import java.sql.*;
import java.util.Date;

/***
 * 项目名称:  MyJDBC 
 * 包：  com.neuedu.jdbc.dao 
 * date:   2025/11/7   14:45  
 * 描述:  
 *  @author : 张金山
 *  作者博客:   https://blog.fulfill.com.cn
 */
public class BaseDao {




    /**
     * 关闭资源
     * @param conn
     * @param stmt
     * @param rs
     */
    public void close(Connection conn, Statement stmt , ResultSet rs) {

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public int executeUpdate(String sql , Object ... objs) {


        Connection connection = null;
        PreparedStatement stmt = null;
        int count = 0;
        try {
            // 1 加载驱动  建立连接
            connection = DBUtils.getConnection();


            // 创建sttm
            stmt = connection.prepareStatement(sql);

            //  执行SQL语句

            // count = stmt.executeUpdate(sql);

            //绑定变量
            if(objs != null && objs.length>0){
                for (int i = 0; i < objs.length; i++) {

                    stmt.setObject(i+1, objs[i]);
                    // if(objs[i] instanceof  Date){
                    //     Date date = (Date)objs[i];
                    //     stmt.setDate(i+1, new java.sql.Date(date.getTime()));
                    //
                    // }else{
                    //     stmt.setObject(i+1, objs[i]);
                    // }
                }
            }
            count = stmt.executeUpdate();


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            // 关闭资源
            this.close(connection, stmt, null);
        }

        return count;

    }
}
